import path from 'path'
import fs from 'fs'

function getFilesAndFoldersInDir(paths, toPath) {
  const items = fs.readdirSync(paths);
  const result = [];
  items.forEach(item => {
    const itemPath = `${paths}/${item}`;
    const stat = fs.statSync(itemPath);
    if (stat.isDirectory()) {
      let data = {
        // 文件夹
        type: 'folder',
        name: item
      }
      let children = getFilesAndFoldersInDir(itemPath, toPath)
      if (children && children.length) {
        data.children = children
      }
      result.push(data);
    } else {
      if(path.extname(item) === '.js') {
        const md = paths + '/' + item;
        const names = paths.slice(paths.lastIndexOf('/') + 1, paths.length);
        result.push({ type: 'file', name: names, title: item, path: md });
      }
    }
  });
  return result;
}

function mkdir(filePath) {
  const dirCache = {};
  const arr = filePath.split('/');
  let dir = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (!dirCache[dir] && !fs.existsSync(dir)) {
      dirCache[dir] = true;
      fs.mkdirSync(dir);
    }
    dir = dir + '/' + arr[i];
  }
  fs.writeFileSync(filePath, '')
}

function getFilesContent(list) {
  list.forEach(folder => {
    if (path.extname(folder.path) === '.js') {
      const names = folder.text.slice(0, folder.text.lastIndexOf('.'));
      const filePath = folder.link + '/' + names + '.adoc';
      if (!fs.existsSync(filePath)) {
        mkdir(filePath);
      }
      fs.writeFileSync(filePath, fs.readFileSync(folder.path));
    }
  })
}

function getCompChildren(fileUrl, toPath) {
  let list = getFilesAndFoldersInDir(fileUrl, toPath)
  // console.log(list);
  list = list.filter(f => f.type === 'folder').map(m => m.children || []).flat().filter(f => f.type === 'file')
  
  const children = [];
  list.forEach(folder => {
    const linkPath = toPath + '/' + folder.name
    children.push({ text: folder.title, link: linkPath, path: folder.path })
  })

  return children;
}

const dataComp = getCompChildren('./core', './docsAdoc')
getFilesContent(dataComp);
console.log(dataComp)
// const content = `module.exports = {
//   '/guide/': ${JSON.stringify(dataGuide)},
//   '/components/': ${JSON.stringify(dataComp)},
//   '/directive/': ${JSON.stringify(dataDire)},
//   '/service/': ${JSON.stringify(dataServ)},
//   '/hooks/': ${JSON.stringify(dataHooks)},
// }`
// fs.writeFile('./docs/components/sidebar.js', content, err => {
//   if (err) {
//   	console.error(err);
//   }
// });

